package com.management.department.teacherinfosystem.Controller;

import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Service.UserService;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 个人中心 + 管理员用户管理接口。
 */
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Validated
public class UserController {

    private final UserService userService;

    /* ============================== 当前用户 ============================== */

    /** 获取当前用户信息 */
    @GetMapping("/me")
    @Transactional(readOnly = true)
    public UserView me() {
        String username = currentUsername();
        User user = userService.findByUsername(username).orElseThrow();
        return UserView.from(user);
    }

    // 目前不再维护手机号/邮箱，这里暂时空实现或用于更新姓名/部门
    @PutMapping("/me")
    public ResponseEntity<?> updateMe(@RequestBody UpdateProfileRequest req) {
        Long id = currentUserId();
        userService.updateUser(id, req.getName(), req.getDepartment(), null);
        return ResponseEntity.ok().build();
    }

    /** 修改密码 */
    @PostMapping("/change_password")
    public ResponseEntity<?> changePwd(@RequestBody @Validated ChangePasswordRequest req) {
        Long id = currentUserId();
        userService.changePassword(id, req.getOldPassword(), req.getNewPassword());
        return ResponseEntity.ok().build();
    }

    /* ============================== 管理员接口 ============================== */

    /** 分页查询 */
    @GetMapping("/list")
    @Transactional(readOnly = true)
    public Map<String, Object> list(@RequestParam(value = "page", defaultValue = "1") int page,
                                    @RequestParam(value = "size", defaultValue = "10") int size) {
        Page<User> p = userService.findAll(PageRequest.of(page - 1, size));
        return Map.of(
                "total", p.getTotalElements(),
                "list", p.getContent().stream().map(UserView::from).collect(Collectors.toList())
        );
    }

    /** 创建用户 */
    @PostMapping
    public UserView create(@RequestBody @Validated CreateUserRequest req) {
        User u = userService.createUser(req.getUsername(), req.getPassword(), req.getName(),
                req.getDepartment(), req.getRole());
        return UserView.from(u);
    }

    /** 更新用户 */
    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody UpdateUserRequest req) {
        userService.updateUser(id, req.getName(), req.getDepartment(), req.getRole());
        return ResponseEntity.ok().build();
    }

    /** 删除用户 */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable("id") Long id) {
        userService.deleteUser(id);
        return ResponseEntity.ok().build();
    }

    /** 单独改角色 */
    @PutMapping("/{id}/role")
    public ResponseEntity<?> changeRole(@PathVariable("id") Long id, @RequestBody Map<String, String> body) {
        String role = body.get("role");
        userService.updateUser(id, null, null, role);
        return ResponseEntity.ok().build();
    }

    /* ============================== 内部工具 ============================== */
    private String currentUsername() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return auth.getName();
    }

    private Long currentUserId() {
        return userService.findByUsername(currentUsername()).orElseThrow().getId();
    }

    /* ============================== DTO / VIEW ============================== */
    @Data
    static class UpdateProfileRequest {
        private String name;
        private String department;
    }

    @Data
    static class ChangePasswordRequest {
        @NotBlank
        private String oldPassword;
        @NotBlank
        @Size(min = 6, max = 30)
        private String newPassword;
    }

    @Data
    static class CreateUserRequest {
        @NotBlank private String username;
        @NotBlank @Size(min = 6) private String password;
        @NotBlank private String name;
        private String department;
        @NotBlank private String role;   // role code
    }

    @Data
    static class UpdateUserRequest {
        private String name;
        private String department;
        private String role;
    }

    @Data
    @AllArgsConstructor
    static class UserView {
        private Long id;
        private String username;
        private String name;
        private String staffNo;
        private String department;
        static UserView from(User u) {
            return new UserView(u.getId(), u.getUsername(), u.getName(),
                    u.getStaffNo(), u.getDepartment());
        }
    }
}
